import { ipcMain } from 'electron';
import {
  IShellLaunchConfig,
  ITerminalService,
} from '../../renderer/terminal-next';
import log from 'electron-log/node';

export function registerTerminalIpcHandlers(terminalService: ITerminalService) {

  ipcMain.handle('terminal:generateSessionId', () => {
    return terminalService.generateSessionId?.();
  });

  ipcMain.handle('terminal:getOptions', () => {
    return terminalService.getOptions?.();
  });

  ipcMain.handle('terminal:check', (_event, sessionIds: string[]) => {
    return terminalService.check?.(sessionIds);
  });

  ipcMain.handle(
    'terminal:attachByLaunchConfig',
    async (
      _event,
      sessionId: string,
      cols: number,
      rows: number,
      launchConfig: IShellLaunchConfig,
      // xterm: IXTerm
    ) => {

      try {
        const result = await terminalService.attachByLaunchConfig(sessionId, cols, rows, launchConfig);
        return result;
      } catch (err) {
        console.error('[main] attachByLaunchConfig error:', err);
        throw err;
      }
    }
  );

  ipcMain.handle(
    'terminal:sendText',
    async (_event, sessionId: string, message: string) => {
      return terminalService.sendText(sessionId, message);
    }
  );

  ipcMain.handle(
    'terminal:resize',
    async (_event, sessionId: string, cols: number, rows: number) => {
      return terminalService.resize(sessionId, cols, rows);
    }
  );

  ipcMain.handle('terminal:disposeById', async (_event, sessionId: string) => {
    return terminalService.disposeById(sessionId);
  });

  ipcMain.handle('terminal:getProcessId', async (_event, sessionId: string) => {
    return terminalService.getProcessId(sessionId);
  });

  ipcMain.handle('terminal:getOS', async () => {
    return terminalService.getOS();
  });

  ipcMain.handle('terminal:getDefaultSystemShell', async () => {
    return terminalService.getDefaultSystemShell();
  });

  ipcMain.handle('terminal:getCodePlatformKey', async () => {
    return terminalService.getCodePlatformKey();
  });

  ipcMain.handle('terminal:getCwd', async (_event, sessionId: string) => {
    return terminalService.getCwd(sessionId);
  });
}
